/*
 * Copyright (c) 2008-2018, RF-Embedded GmbH
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "QrfeMessageQueue.h"

#include <QMutexLocker>
#include <QTime>

using namespace QrfeReaderInterface;

#define MAX_WAIT_TIME           10

/**
 * @brief QrfeMessageQueue::QrfeMessageQueue constructs a new message queue
 * @param parent    Parent object
 */
QrfeMessageQueue::QrfeMessageQueue(QObject* parent)
    : QObject(parent)
{
    m_messageMutex = new QMutex(QMutex::Recursive);
}

/**
 * @brief QrfeMessageQueue::~QrfeMessageQueue Destructor
 */
QrfeMessageQueue::~QrfeMessageQueue()
{
    delete m_messageMutex;
}

/**
 * @brief QrfeMessageQueue::clearMessage removes message from message queue
 * @param id    ID of the message to remove
 */
void QrfeMessageQueue::clearMessage (int id)
{
    m_messageMutex->lock();
    m_messages.remove(id);
    m_messageMutex->unlock();
}

/**
 * @brief QrfeMessageQueue::waitForMessage waits for a specified message
 * @param id    ID of the message to wait for
 * @param msecs Maximum waitung time
 * @param ok    Result of the operation
 * @return The message
 */
QByteArray QrfeMessageQueue::waitForMessage (int id, uint msecs, bool *ok)
{
    QByteArray ret;

    *ok = false;

    QTime t;
    t.start();
    while(1)
    {
        uint elapsed = t.elapsed();
        if(elapsed > msecs){
            return ret;
        }

        QMutexLocker lock(&m_waitMutex);
        if(!m_messages.contains(id))
        {
            *ok = m_messageAvailable.wait(&m_waitMutex, msecs - elapsed);
        }

        if(m_messages.contains(id) && m_messages.value(id).size() > 0)
        {
            m_messageMutex->lock();
            ret = m_messages[id].takeFirst();
            if(m_messages.value(id).size() == 0)
                m_messages.remove(id);
            m_messageMutex->unlock();
            *ok = true;
            return ret;
        }
    }

    return ret;
}

/**
 * @brief QrfeMessageQueue::enqueueMessage enqueues the given message
 * @param id        ID of the message to enqueue
 * @param message   The message
 */
void QrfeMessageQueue::enqueueMessage (int id, const QByteArray& message)
{
    QMutexLocker lock(&m_waitMutex);
    m_messageMutex->lock();
    m_messages[id].append(message);
    m_messageMutex->unlock();
    m_messageAvailable.wakeAll();
}
